package cn.happyjava.springbootsecurity.service;

import cn.happyjava.springbootsecurity.pojo.User;
import cn.happyjava.springbootsecurity.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepository.findByUsername(username);
    }

    public User findByUsernameAndPsd(String userName, String psd) throws Exception {
        User user = userRepository.findByUsernameAndPassword(userName, psd);
        if (user == null) {
            throw new Exception("用户名或者密码不正确");
        }
        return user;
    }

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public User findByApiKey(String apiKey) {
        return userRepository.findByApiKey(apiKey);
    }
}
